package com.cicadamob.contact.api;

import java.io.File;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.cicadamob.contact.api.Utils.ContactConfig;
import com.cicadamob.contact.api.Utils.ExecutorService.ThreadPoolManager;
import com.cicadamob.contact.api.group.asynctask.AddGroupZipRequetRunnable;
import com.cicadamob.contact.api.group.asynctask.AddMemberRunnable;
import com.cicadamob.contact.api.group.asynctask.DelGroupRunnable;
import com.cicadamob.contact.api.group.asynctask.DelMemberRunnable;
import com.cicadamob.contact.api.group.asynctask.EditGroupRunnable;
import com.cicadamob.contact.api.group.asynctask.LoadGroup;
import com.cicadamob.contact.api.group.asynctask.LoadGroupMember;
import com.cicadamob.contact.api.group.asynctask.LoadGroupName;
import com.cicadamob.contact.api.group.asynctask.LoadSingleGroup;
import com.cicadamob.contact.api.group.bean.Group;
import com.cicadamob.contact.api.group.bean.ResultModel;
import com.cicadamob.contact.api.group.dao.Group_Db_Dao;
import com.cicadamob.contact.api.service.APIAsynTask;
import com.cicadamob.contact.api.service.APPContactDao;
import com.cicadamob.contact.api.service.BaseResultModel;
import com.cicadamob.contact.api.service.Contact;
import com.cicadamob.contact.api.service.ContactDbHelper;
import com.cicadamob.contact.api.service.DoInBackground;
import com.cicadamob.contact.api.service.DownLoadContactAsyTask;
import com.cicadamob.contact.api.service.FindAllSysContactRunnable;
import com.cicadamob.contact.api.service.ICallBack;
import com.cicadamob.contact.api.service.LoadContactDataRunnable;
import com.cicadamob.contact.api.service.SaveToLocalUtils;
import com.cicadamob.contact.api.service.SearchRunnable;
import com.cicadamob.contact.api.service.SysContactDao;
import com.cicadamob.contact.api.service.Org;
import com.cicadamob.contact.api.service.UpdateCompanyRunnable;
import com.cicadamob.contact.api.service.WriteLog;
/**
 * 要传CallBack的方法只能在UI线程调用
 * BaseResultModel的rCode为0表示操作成功
 * BaseResultModel的rData是操作返回的结果，rData的数据类型是BaseResultModel传的泛型
 * BaseResultModel的description是操作结果描述
 * @author lvbo
 *
 */
public class ContactUtils {
	
	private static ContactUtils instance;
	
	private ContactUtils(){
		
	}
	
	public static ContactUtils getInstance(){
		if(instance==null) instance=new ContactUtils();
		
		return instance;
	}
	
	/**
	 * 下载通讯录
	 * @param context
	 * @param callBack
	 */
	public void downLoadContact(Context context,ICallBack<Integer> callBack){
		StringBuilder sb=new StringBuilder();
		sb.append("方法：downLoadContact(),参数：，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		
		DownLoadContactAsyTask asynTask=new DownLoadContactAsyTask(context, callBack);
		asynTask.execute();
		
	}
	
	/***
	 * 删除数据库
	 * @param mApplication
	 * @return
	 */
	 public boolean delDataBase(Application mApplication){
		 boolean delResult=false;
		 File file = ContactConfig.getContext().getFileStreamPath( ContactDbHelper.DBFILE );
			if (file.exists())
				delResult=file.delete();
				
		 return delResult;
	 }
	
	/**
	 * 增量更新通讯录
	 * @param mContext
	 * @param callBack
	 */
	public void updateContact(Context mContext, final ICallBack<Integer> callBack){

		StringBuilder sb=new StringBuilder();
		sb.append("方法：updateContact(Context mContext, final ICallBack<Integer> callBack),参数：，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		int MESSAGE_WHAT=100;
		Handler myHandler=new Handler(){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				
                    if(callBack!=null) callBack.respone(new BaseResultModel<Integer>(0, "通讯录增量更新完成", 11));
                    
                    StringBuilder sb=new StringBuilder();
            		sb.append("方法：updateContact(),action：返回，返回数据：rCode=0");
            		WriteLog.WriteLocationListLogSDK(sb.toString());
			}
			
		};
		
		ThreadPoolManager.getInstance().addTask(new UpdateCompanyRunnable(mContext, myHandler, MESSAGE_WHAT));
	}
	
	
	/**
	 * 获取组织下的成员与组织
	 * @param mContext
	 * @param tableType 等于1为客户，2为同事
	 * @param OnlyInstalled
	 * @param callBack
	 */
	public void getOrgChild(Context mContext,final int treeId,final int tableType,final boolean OnlyInstalled,final ICallBack<ArrayList<Object>> callBack){
		StringBuilder sb=new StringBuilder();
		sb.append("方法：getContactData(),参数：treeId="+treeId+",tableType="+tableType+",OnlyInstalled"+OnlyInstalled+"，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		
		int MESSAGE_WHAT=100;
		Handler myHandler=new Handler(){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				
				StringBuilder sb=new StringBuilder();
        		sb.append("方法：getContactData(),action：返回，返回数据：rCode=0");
        		WriteLog.WriteLocationListLogSDK(sb.toString());
                
        		if(callBack!=null) callBack.respone(new BaseResultModel<ArrayList<Object>>(0, "获取成功", (ArrayList<Object>) msg.obj));
                    
			}
			
		};
		
		String personTable=null;
		String treeTable="";
		//获取数据库数据显示
		if(tableType==1){//客户
			treeTable=ContactDbHelper.COMPANY_CLIENT_TREE_TABLE;
			personTable=ContactDbHelper.COMPANY_CLIENT_PERSON_TABLE;
			
		}else if(tableType==2){//同事
			treeTable=ContactDbHelper.COMPANY_TREE_DATABASE;
			personTable=ContactDbHelper.COMPANY_PERSON_DATABASE;
			
		}
		
		ThreadPoolManager.getInstance().addTask(new LoadContactDataRunnable(mContext,myHandler, treeId, treeTable, personTable, MESSAGE_WHAT,false));
	}
	
	
	/**
	 * 获取最高级的组织
	 * @param mContext
	 * @param treeId 组织id，如果传-1则获取顶层组织
	 * @param treeTable ContactDbHelper.COMPANY_TREE_DATABASE或者ContactDbHelper.COMPANY_CLIENT_TREE_TABLE
	 * @param OnlyInstalled
	 * @param callBack
	 */
	public void getTopOrg(Context mContext,final int tableType,final ICallBack<Org> callBack){
		
		
		StringBuilder sb=new StringBuilder();
		sb.append("方法：getContactTopTree(),参数：treeTable="+tableType+"，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
				
		DoInBackground doHandler=new DoInBackground() {
			
			@Override
			public BaseResultModel<Org> doInBackground(Context mContext) {
				// TODO Auto-generated method stub
				ArrayList<Org> treeList=null;//下属组织
				
				String treeTable="";
				
				//获取数据库数据显示
				if(tableType==1){//客户
					treeTable=ContactDbHelper.COMPANY_CLIENT_TREE_TABLE;
				}else if(tableType==2){//同事
					treeTable=ContactDbHelper.COMPANY_TREE_DATABASE;
				}
					treeList=ContactDbHelper.getInstance().queryTop(treeTable);
				
					StringBuilder sb=new StringBuilder();
	        		sb.append("方法：getContactTopTree(),action：返回，返回数据：rCode=0");
	        		WriteLog.WriteLocationListLogSDK(sb.toString());
	        		
				if(treeList ==null || treeList.size()==0) 
					return new BaseResultModel<Org>(-1, "获取最顶层组织失败", null); 
				else
					return new BaseResultModel<Org>(0, "获取最顶层组织成功", treeList.get(0));
				
				
			}
		};
		
		APIAsynTask task=new APIAsynTask(mContext, callBack, doHandler);
		task.execute();
	}
	
	
	/**
	 * 
	 * @param mContext
	 * @param type 值选如下之一
	 * SearchContactsUtil.SEARCH_PERSON搜索个人
	 *SearchContactsUtil.SEARCH_COMPANY_PERSON搜索同事
	 *SearchContactsUtil.SEARCH_CLIENT_PERSON搜索客户
	 *SearchContactsUtil.SEARCH_GROUP搜索群组
	 *SearchContactsUtil.SEARCH_GROUP_MEMBER搜索群组成员
	 *SearchContactsUtil.SEARCH_ALL搜索全部
	 * @param keyWorke 模糊搜索关键字
	 * @param groupId 当type=SearchContactsUtil.SEARCH_GROUPID_MEMBER时才有用
	 * @param callBack
	 */
	public void searchMembers( final Context mContext, final int type, final String keyWorke, final String groupId,final boolean  onlyInstalled,final ICallBack<Map<Integer,ArrayList<Contact>>> callBack){
		
		StringBuilder sb=new StringBuilder();
		sb.append("方法：searchMembers(),参数：type="+type+",keyWorke="+keyWorke+",groupId"+groupId+"，onlyInstalled="+onlyInstalled+"，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		
       DoInBackground doHandler=new DoInBackground() {
			
			@Override
			public BaseResultModel<Map<Integer,ArrayList<Contact>>> doInBackground(Context mContext) {
				// TODO Auto-generated method stub
				BaseResultModel<Map<Integer,ArrayList<Contact>>> data=new SearchRunnable(mContext, null, type, keyWorke, groupId, onlyInstalled,callBack).doInBackground(mContext);
				
				StringBuilder sb=new StringBuilder();
        		sb.append("方法：searchMembers(),action：返回，返回数据：rCode=0");
        		WriteLog.WriteLocationListLogSDK(sb.toString());
        		
				return data;
			}
		};
		
		APIAsynTask task=new APIAsynTask(mContext, callBack, doHandler);
		task.execute();
		
		
//		Handler myHandler=new Handler(){
//
//			@Override
//			public void handleMessage(Message msg) {
//				// TODO Auto-generated method stub
//				super.handleMessage(msg);
//				
//				BaseResultModel<Map<Integer,ArrayList<Contact>>> data=(BaseResultModel<Map<Integer, ArrayList<Contact>>>) msg.obj;
//			    if(callBack!=null && data!=null) callBack.respone(data);
//			    Toast.makeText(mContext, "测试", Toast.LENGTH_LONG).show();
//			}
//			
//		};
//		
//		ThreadPoolManager.getInstance().addTask(new SearchRunnable(mContext, myHandler, type, keyWorke, groupId, onlyInstalled,callBack));
	}
	
	/**
	 * 获取群组列表,只能在UI线程调用
	 * @param mContext
	 * @param callBack
	 */
	public void getGroups(Context mContext,final boolean isfromNet,final ICallBack<ArrayList<Group>> callBack){
		
		StringBuilder sb=new StringBuilder();
		sb.append("方法：getGroups(),参数：，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		
		int LOAD_GROUPS_ACTION=1003;
		Handler myHandler=new Handler(){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				ResultModel dataModel=(ResultModel) msg.obj;
				
                if(callBack!=null) callBack.respone(new BaseResultModel(dataModel.getRetcode(), "获取成功", (ArrayList<Group>) dataModel.getResultData()));
                 StringBuilder sb=new StringBuilder();
                 sb.append("方法：getGroups(),action：返回，返回数据：rCode=0");
            	 WriteLog.WriteLocationListLogSDK(sb.toString());
			}
			
		};
		ThreadPoolManager.getInstance().addTask(new LoadGroup(myHandler, mContext, LOAD_GROUPS_ACTION,isfromNet));
	}
	
//	/**
//	 * 刷新群组列表,只能在UI线程调用
//	 * @param mContext
//	 * @param keyWorke
//	 * @param callBack
//	 */
//	public void refreshGroups(Context mContext,final ICallBack<ArrayList<Group>> callBack){
//		StringBuilder sb=new StringBuilder();
//		sb.append("方法：refreshGroups(),参数：，action：请求");
//		WriteLog.WriteLocationListLogSDK(sb.toString());
//		
//		int LOAD_GROUPS_ACTION=1003;
//		Handler myHandler=new Handler(){
//
//			@Override
//			public void handleMessage(Message msg) {
//				// TODO Auto-generated method stub
//				super.handleMessage(msg);
//				ResultModel dataModel=(ResultModel) msg.obj;
//				
//				StringBuilder sb=new StringBuilder();
//                sb.append("方法：refreshGroups(),action：返回，返回数据：rCode=0");
//           	    WriteLog.WriteLocationListLogSDK(sb.toString());
//           	    
//				if(dataModel.getRetcode()==0 || dataModel.getRetcode()==3)
//                    if(callBack!=null) callBack.respone(new BaseResultModel(0, "刷新群组列表成功", (ArrayList<Group>) dataModel.getResultData()));
//				else
//					if(callBack!=null) callBack.respone(new BaseResultModel(-1, "刷新群组列表失败", null));
//				
//				
//			}
//			
//		};
//		ThreadPoolManager.getInstance().addTask(new LoadGroup(myHandler, mContext, LOAD_GROUPS_ACTION,true));
//	}
	
	
//	/**
//	 * 获取每个群组有多少号人，为了显示群组头像
//	 * @param mContext
//	 * @param callback
//	 */
//	public void getGroupMemberCounts(Context mContext,ICallBack<HashMap<String,Integer>> callback){
//		 DoInBackground doHandler=new DoInBackground() {
//				
//				@Override
//				public BaseResultModel<HashMap<String,Integer>> doInBackground(Context mContext) {
//					// TODO Auto-generated method stub
//					Group_Db_Dao dbHelper = Group_Db_Dao.getInstance(mContext);
//					HashMap<String, Integer> groupCountMap=dbHelper.queryGroupCount();
//					return new BaseResultModel<HashMap<String,Integer>>(0, "获取每个群组有多少号人，为了显示群组头像", groupCountMap);
//				}
//			};
//			
//			APIAsynTask task=new APIAsynTask(mContext, callback, doHandler);
//			task.execute();
//	}
	
	/**
	 * 获取群组成员，只能在ui线程调用
	 * @param mContext
	 * @param OnlyInstalled 是否只返回已经安装客户端的用户
	 * @param groupId
	 * @param callBack
	 */
	public void getGroupMembers(Context mContext,final String groupId,boolean OnlyInstalled,final ICallBack<ArrayList<Contact>> callBack){
		
		StringBuilder sb=new StringBuilder();
		sb.append("方法：getGroupMembers(),参数：groupId="+groupId+",OnlyInstalled="+OnlyInstalled+"，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		
		int LOAD_GROUP_MEMBER_ACTION=104;
		Handler myHandler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				
				ResultModel dataModel=(ResultModel) msg.obj;
				
				StringBuilder sb=new StringBuilder();
                sb.append("方法：getGroupMembers(),action：返回，返回数据：rCode=0");
           	    WriteLog.WriteLocationListLogSDK(sb.toString());
           	    
				if(dataModel.getRetcode()==0 || dataModel.getRetcode()==3)
                    if(callBack!=null) callBack.respone(new BaseResultModel(0, "获取成功", (ArrayList<Contact>) dataModel.getResultData()));
				else
					if(callBack!=null) callBack.respone(new BaseResultModel(-1, "获取失败", null));
				
			}
		};
		ThreadPoolManager.getInstance().addTask(new LoadGroupMember(myHandler, LOAD_GROUP_MEMBER_ACTION, mContext, groupId,false,OnlyInstalled));
	}
	
	/**
	 * 刷新某群组信息
	 * @param mContext
	 * @param groupId
	 * @param callBack
	 */
	public void updateGroupMembers(Context mContext,final String groupId,final ICallBack<ArrayList<Contact>> callBack){
		
		StringBuilder sb=new StringBuilder();
		sb.append("方法：refreshGroupInfo(),参数：groupId="+groupId+"，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		
		int LOAD_GROUP_MEMBER_ACTION=104;
		Handler myHandler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				
				ResultModel dataModel=(ResultModel) msg.obj;
				
				StringBuilder sb=new StringBuilder();
                sb.append("方法：refreshGroupInfo(),action：返回，返回数据：rCode=0");
           	    WriteLog.WriteLocationListLogSDK(sb.toString());
           	    
				if(dataModel.getRetcode()==0)
                    if(callBack!=null) callBack.respone(new BaseResultModel(0, "获取成功", (ArrayList<Contact>) dataModel.getResultData()));
				else
					if(callBack!=null) callBack.respone(new BaseResultModel(dataModel.getRetcode(), "获取失败", null));
				
			}
		};
		ThreadPoolManager.getInstance().addTask(new LoadGroupMember(myHandler, LOAD_GROUP_MEMBER_ACTION, mContext, groupId,true,false));
	}
	
	
	/**
	 * 获取单个群组（从网络获取）
	 * @param mContext
	 * @param groupId
	 * @param callBack
	 */
	public void updateGroup(Context mContext,final String groupId,final ICallBack<Group> callBack){
		StringBuilder sb=new StringBuilder();
		sb.append("方法：updateGroup(),参数：groupId="+groupId+"，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		
		int LOAD_GROUP_MEMBER_ACTION=104;
		Handler myHandler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				
				ResultModel dataModel=(ResultModel) msg.obj;
				
				StringBuilder sb=new StringBuilder();
                sb.append("方法：updateGroup(),action：返回，返回数据：rCode=0");
           	    WriteLog.WriteLocationListLogSDK(sb.toString());
           	    flag=false;
				if(dataModel.getRetcode()==0){
//					mGroup=(Group) dataModel.getResultData();
                    if(callBack!=null) callBack.respone(new BaseResultModel(0, "获取成功", (Group) dataModel.getResultData()));
				}else{
					if(callBack!=null) callBack.respone(new BaseResultModel(dataModel.getRetcode(), "获取失败", null));
				}
			}
		};
		ThreadPoolManager.getInstance().addTask(new LoadSingleGroup(myHandler, LOAD_GROUP_MEMBER_ACTION, mContext, groupId,true,false));;
//		while (flag) {
//			
//		}
//		return ;
	}
	
	private static boolean flag=true;
	
	/**
	 * 获取最新的群组名称
	 * @param mContext
	 * @param groupId
	 * @param callBack
	 */
	public void getGroupById(Context mContext,String groupId,final ICallBack<Group> callBack){
		StringBuilder sb=new StringBuilder();
		sb.append("方法：getGroupName(),参数：groupId="+groupId+"，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		
		int LOAD_GROUP_NAME_ACTION=104;
		Handler myHandler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				StringBuilder sb=new StringBuilder();
                sb.append("方法：getGroupName(),action：返回，返回数据：rCode=0");
           	    WriteLog.WriteLocationListLogSDK(sb.toString());
           	    
                if(callBack!=null) callBack.respone(new BaseResultModel(0, "获取成功", (Group) msg.obj));
			}
		};
		ThreadPoolManager.getInstance().addTask(new LoadGroupName(myHandler, LOAD_GROUP_NAME_ACTION, mContext, groupId));
	}
	
	
	/**
	 * 获取全部联系人
	 * @param mContext
	 * @param iCallBack
	 */
	public void getSystemContact(Context mContext,boolean onlyInstalled,final ICallBack<List<Contact>> iCallBack){
		getSystemContact(mContext, onlyInstalled, false, iCallBack);
	}
	
	public void getSystemContact(Context mContext,boolean onlyInstalled,final boolean isCommon,final ICallBack<List<Contact>> iCallBack){
		
		StringBuilder sb=new StringBuilder();
		sb.append("方法：getSystemContact(),参数：onlyInstalled="+onlyInstalled+"，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		
		int MESSAGE_WHAT_ALL_LIST=104;
		Handler myHandler=new Handler(){
			@SuppressWarnings("unchecked")
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
                
				StringBuilder sb=new StringBuilder();
                sb.append("方法：getSystemContact(),action：返回，返回数据：rCode=0");
           	    WriteLog.WriteLocationListLogSDK(sb.toString());
           	    
				if(iCallBack!=null) iCallBack.respone(new BaseResultModel<List<Contact>>(isCommon?1:0, "获取联系人成功", (List<Contact>) msg.obj));
				
			}
		};
		ThreadPoolManager.getInstance().addTask(new FindAllSysContactRunnable(myHandler, mContext, MESSAGE_WHAT_ALL_LIST,onlyInstalled,isCommon));
	}
	
	/**
	 * 更新联系人安装客户端情况
	 * @param mContext
	 */
	public void refreshInstalled(Context mContext,final ICallBack<Integer> callBack){
		StringBuilder sb=new StringBuilder();
		sb.append("方法：refreshInstalled(),参数：，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		
		DoInBackground doHandler=new DoInBackground() {
			
			@Override
			public BaseResultModel<Integer> doInBackground(Context mContext) {
				// TODO Auto-generated method stub
				boolean re=APPContactDao.getUnInstallStatusOfContact(mContext);
				
				StringBuilder sb=new StringBuilder();
                sb.append("方法：getSystemContact(),action：返回，返回数据：rCode=0");
           	    WriteLog.WriteLocationListLogSDK(sb.toString());
           	    
				if(re){
					
					return new BaseResultModel<Integer>(0, "更新联系人安装状态成功", null);
				}else{
					return new BaseResultModel<Integer>(-1, "更新联系人安装状态失败", null);
				}
				 
			}
		};
		
		APIAsynTask task=new APIAsynTask(mContext, callBack, doHandler);
		task.execute();
	}
	
	/**
	 * 删除群组
	 * @param mContext
	 * @param Group 包含group_id
	 * @param callBack
	 */
	public void quitGroup(Context mContext,String mGroupId, final ICallBack<ArrayList<Group>> callBack){
		
		StringBuilder sb=new StringBuilder();
		sb.append("方法：delGroup(),参数：mGroup.group_id="+mGroupId+"，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		
		int DEL_GROUP_ACTION=104;
		Handler myHandler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				
				ResultModel dataModel=(ResultModel) msg.obj;
				StringBuilder sb=new StringBuilder();
                sb.append("方法：delGroup(),action：返回，返回数据：rCode="+dataModel.getRetcode());
           	    WriteLog.WriteLocationListLogSDK(sb.toString());
				if(dataModel.getRetcode()==0 )
                    if(callBack!=null) callBack.respone(new BaseResultModel(0, "删除群组成功", dataModel.getResultData()));
				else
					if(callBack!=null) callBack.respone(new BaseResultModel(dataModel.getRetcode(), "删除群组失败", null));
				
			}
		};
		ThreadPoolManager.getInstance().addTask(new DelGroupRunnable(myHandler, DEL_GROUP_ACTION, mContext, mGroupId, false));
	}
	
	/**
	 * 解散群组
	 * @param mContext
	 * @param mGroup
	 * @param callBack
	 */
	public void dissolveGroup(Context mContext,String mGroupId, final ICallBack<ArrayList<Group>> callBack){
		StringBuilder sb=new StringBuilder();
		sb.append("方法：dissolveGroup(),参数：mGroup.group_id="+mGroupId+"，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		int DEL_GROUP_ACTION=104;
		Handler myHandler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				
				ResultModel dataModel=(ResultModel) msg.obj;
				
				StringBuilder sb=new StringBuilder();
                sb.append("方法：dissolveGroup(),action：返回，返回数据：rCode="+dataModel.getRetcode());
           	    WriteLog.WriteLocationListLogSDK(sb.toString());
				
				if(dataModel.getRetcode()==0 || dataModel.getRetcode()==3)
                    if(callBack!=null) callBack.respone(new BaseResultModel(0, "解散群组成功", dataModel.getResultData()));
				else
					if(callBack!=null) callBack.respone(new BaseResultModel(-1, "解散群组失败", dataModel.getRetcode()));
				
			}
		};
		ThreadPoolManager.getInstance().addTask(new DelGroupRunnable(myHandler, DEL_GROUP_ACTION, mContext, mGroupId, true));
	}
	
	/**
	 * 创建群组
	 * @param mContext
	 * @param groupName
	 * @param groupImagePath 本地图片路径
	 * @param contactsForAdd 群组成员
	 * @param httpURLConnectioncon
	 * @param callBack
	 */
	public void createGroup(Context mContext,String groupName, String groupImagePath,List<Contact> contactsForAdd,HttpURLConnection httpURLConnectioncon, final ICallBack<ResultModel> callBack){
		StringBuilder sb=new StringBuilder();
		sb.append("方法：addGroup(),参数：groupName="+groupName+",groupImagePath="+groupImagePath+",contactsForAdd="+contactsForAdd+"，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		
		int WHAT_ADD_GROUP=104;
		Handler myHandler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				
				ResultModel dataModel=(ResultModel) msg.obj;
				
				StringBuilder sb=new StringBuilder();
                sb.append("方法：addGroup(),action：返回，返回数据：rCode="+dataModel.getRetcode());
           	    WriteLog.WriteLocationListLogSDK(sb.toString());
           	    
                if(callBack!=null) callBack.respone(new BaseResultModel(dataModel.getRetcode(), "创建群组成功", dataModel));
			}
		};
		
		ThreadPoolManager.getInstance().addTask(new AddGroupZipRequetRunnable(myHandler, WHAT_ADD_GROUP, mContext, groupName, groupImagePath, contactsForAdd, httpURLConnectioncon));
	}
	
	/**
	 * 删除群组成员
	 * @param mContext
	 * @param groupId
	 * @param mContact 必须包含idInGroup
	 * @param callBack
	 */
	public void delGroupMember(Context mContext,String groupId,Contact mContact,final ICallBack<ArrayList<Contact>> callBack){
		
		StringBuilder sb=new StringBuilder();
		sb.append("方法：delGroupMember(),参数：groupId="+groupId+",mContact.idInGroup="+mContact.getIdInGroup()+"，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		
		int DEL_GROUP_MEMBER_ACTION=104;
		Handler myHandler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				ResultModel dataModel=(ResultModel) msg.obj;
				
				StringBuilder sb=new StringBuilder();
                sb.append("方法：delGroupMember(),action：返回，返回数据：rCode="+dataModel.getRetcode());
           	    WriteLog.WriteLocationListLogSDK(sb.toString());
           	    
               if(callBack!=null) callBack.respone(new BaseResultModel(dataModel.getRetcode(), "删除群组成员成功", dataModel.getResultData()));
				
			}
		};
		ThreadPoolManager.getInstance().addTask(new DelMemberRunnable(myHandler, DEL_GROUP_MEMBER_ACTION, mContext, groupId, mContact));
	}
	
	/**
	 * 添加群组成员
	 * @param mContext
	 * @param groupId
	 * @param selectedcontacts 将要添加到群组的成员列表
	 * @param callBack
	 */
	public void addGroupMember(Context mContext,String groupId,List<Contact> selectedcontacts,final ICallBack<ArrayList<Contact>> callBack){
		
		StringBuilder sb=new StringBuilder();
		sb.append("方法：addGroupMember(),参数：groupId="+groupId+",selectedcontacts.size="+selectedcontacts.size()+"，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		
		int ADD_GROUP_MEMBER_ACTION=104;
		Handler myHandler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				ResultModel dataModel=(ResultModel) msg.obj;
				
				StringBuilder sb=new StringBuilder();
                sb.append("方法：addGroupMember(),action：返回，返回数据：rCode="+dataModel.getRetcode());
           	    WriteLog.WriteLocationListLogSDK(sb.toString());
           	    
                if(callBack!=null) callBack.respone(new BaseResultModel(dataModel.getRetcode(), "添加群组成员成功", dataModel.getResultData()));
				
			}
		};
		
		AddMemberRunnable runable=new AddMemberRunnable(myHandler, ADD_GROUP_MEMBER_ACTION, mContext, groupId,selectedcontacts);
		runable.run();
	}
	
	/**
	 * 修改群组
	 * @param mContext
	 * Group包含 groupId、group_name、group_imagePath
	 * @param callBack
	 */
	public void editGroup(Context mContext,Group mGroup,final ICallBack<ResultModel> callBack){
		
		StringBuilder sb=new StringBuilder();
		sb.append("方法：editGroup(),参数：mGroup.groupId="+mGroup.getGroup_id()+",mGroup.group_name="+mGroup.getGroup_name()+",group_imagePath="+mGroup.getImagePath()+"，action：请求");
		WriteLog.WriteLocationListLogSDK(sb.toString());
		
		int WHAT_EDIT_GROUP=105;
		Handler myHandler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				
				ResultModel dataModel=(ResultModel) msg.obj;
				
				StringBuilder sb=new StringBuilder();
                sb.append("方法：editGroup(),action：返回，返回数据：rCode="+dataModel.getRetcode());
           	    WriteLog.WriteLocationListLogSDK(sb.toString());
				
				if(dataModel.getRetcode()==0)
                    if(callBack!=null) callBack.respone(new BaseResultModel(0, "修改群组成员成功", dataModel));
				else
					if(callBack!=null) callBack.respone(new BaseResultModel(-1, "修改群组成员失败", dataModel));
				
			}
		};
		
		ThreadPoolManager.getInstance().addTask(new EditGroupRunnable(myHandler, WHAT_EDIT_GROUP, mContext, mGroup.getGroup_name(), mGroup.getImagePath(), mGroup.getGroup_id()));
	}
	
	/**
	 * 将联系人和联系电话，存放到本地
	 * @param ctx
	 * @param name
	 * @param phone
	 * @param callBack
	 */
	public void saveContactToLocal(Context ctx,String name,String phone,ICallBack<Boolean> callBack){
		boolean result=	SaveToLocalUtils.saveToLocal(ctx, name, phone);
		if(callBack!=null){
			callBack.respone(new BaseResultModel<Boolean>(0, "将联系人和联系电话，存放到本地", result));
		}
	}
	
	/**
	 * 修改某群组的状态，是否为新群组的状态
	 * @param ctx
	 * @param groupId
	 * @param callBack
	 */
	public void updateGroupStatus(Context ctx,String groupId,ICallBack<Boolean> callBack){
		Group_Db_Dao.getInstance(ctx).updateGroupStateById(groupId);
		if(callBack!=null){
			callBack.respone(new BaseResultModel<Boolean>(0, "", true));
		}
	}
	
	/**
	 * 是否能打开通讯录数据库
	 * @return
	 */
	public boolean openContactDB(){
		
		return ContactDbHelper.getInstance().canOpen();
	}
	
	/**
	 * 是否为群组创建者
	 * @param mContext
	 * @param tel
	 * @param groupId
	 * @return
	 */
	public boolean isGroupCreater(Context mContext,String tel,String groupId){
		Group_Db_Dao dbHelper=Group_Db_Dao.getInstance(mContext);
		boolean isOwer = dbHelper.isGroupCreater(tel, groupId);
		return isOwer;
	}

	
	/**
	 * 根据群组id和成员的手机号码获取某群组的成员，如果找不到就返回null
	 * @param mContext
	 * @param groupId
	 * @param tel
	 * @param callback
	 */
	public Contact getMemberByGroupIdAndTel(Context mContext, String groupId, String tel){
//		 DoInBackground doHandler=new DoInBackground() {
//				
//				@Override
//				public BaseResultModel<Contact> doInBackground(Context mContext) {
//					// TODO Auto-generated method stub
//					Group_Db_Dao dbHelper = Group_Db_Dao.getInstance(mContext);
//					Contact mContact=	dbHelper.getMemberByGroupIdAndTel(groupId, tel);
//					return new BaseResultModel<Contact>(0, "获取成功", mContact);
//				}
//			};
//			
//			APIAsynTask task=new APIAsynTask(mContext, callback, doHandler);
//			task.execute();
		Group_Db_Dao dbHelper = Group_Db_Dao.getInstance(mContext);
		Contact mContact=	dbHelper.getMemberByGroupIdAndTel(groupId, tel);
		return mContact;
	}
	
	/**
	 * 根据群组id   查询 群组url 
	 * @param mContext
	 * @param groupId
	 * @return
	 */
	public String queryGroupPhoto(Context mContext, String groupId){
//		 DoInBackground doHandler=new DoInBackground() {
//				
//				@Override
//				public BaseResultModel<Contact> doInBackground(Context mContext) {
//					// TODO Auto-generated method stub
//					Group_Db_Dao dbHelper = Group_Db_Dao.getInstance(mContext);
//					Contact mContact=	dbHelper.getMemberByGroupIdAndTel(groupId, tel);
//					return new BaseResultModel<Contact>(0, "获取成功", mContact);
//				}
//			};
//			
//			APIAsynTask task=new APIAsynTask(mContext, callback, doHandler);
//			task.execute();
		Group_Db_Dao dbHelper = Group_Db_Dao.getInstance(mContext);
		String photoPath=	dbHelper.queryGroupPhoto(groupId);
		return photoPath;
	}
	
	/**
	 * 删除所有群组
	 * @param mContext
	 * @param groupId
	 * @return
	 */
	public void delAllGroup(Context mContext){
		Group_Db_Dao.getInstance(mContext).delAllGroup();
	}
	
	/**
	 * 根据群组id删除群组
	 * @param mContext
	 * @param groupId
	 * @return
	 */
	public int quitGroup(Context mContext,String groupId){
		return Group_Db_Dao.getInstance(mContext).delGroupById(groupId);
	}
	
	/**
	 * 根据成员id删除成员
	 * @param mContext
	 * @param groupId
	 * @return
	 */
	public int delMemberByMid(Context mContext,String mid){
		return Group_Db_Dao.getInstance(mContext).delMemberByMid(mid);
	}
	
	/**
	 * 根据群组id修改群组状态
	 * @param mContext
	 * @param groupId
	 * @return
	 */
	public void updateGroupStateById(Context mContext,String groupId,int isNew){
		 Group_Db_Dao.getInstance(mContext).updateGroupStateById(groupId, isNew);
	}
	
	/**
	 * 根据群组id 号码去查询成员id
	 * @param mContext
	 * @param groupId
	 * @return
	 */
	public String updateGroupStateById(Context mContext,String groupId,String phone){
		return Group_Db_Dao.getInstance(mContext).queryMemberIdByPhone(groupId, phone);
	}
	
	
	
	/**
	 * 根据群组id查询群组名称及头像路径
	 * @param mContext
	 * @param groupId
	 * @return
	 */
	public Group queryGroupNameAndImage(Context mContext,String groupId){
		return Group_Db_Dao.getInstance(mContext).queryGroupNameAndImage(groupId);
	}
	
	
	/**
	 * 根据分组查询全部联系人
	 * @param mContext
	 * @param groupId
	 * @return
	 */
	public List<Contact> queryAllMemberByGroupId(Context mContext,String groupId){
		return Group_Db_Dao.getInstance(mContext).queryAllMemberByGroupId(groupId);
	}
	
	
	/**
	 * 根据群组id 号码去查询成员id
	 * @param mContext
	 * @param groupId
	 * @param phone
	 * @return
	 */
	public String queryMemberIdByPhone(Context mContext,String groupId,String phone){
		return Group_Db_Dao.getInstance(mContext).queryMemberIdByPhone(groupId, phone);
	}
	
	/**
	 * 根据联系人id查找该联系人的所有号码
	 * <p>
	 * 
	 * @author xmq
	 * @param mContext
	 * @param userId
	 * @return
	 */
	public List<String> getPhonesByUserId(Context mContext, String userId) {
		return APPContactDao.getPhones(mContext, userId);
	}
}
